import React, { PureComponent } from "react";
import {
    Text,
    View,
    ScrollView,
    FlatList,
    TouchableOpacity,
    StyleSheet,
    RefreshControl, Platform
} from "react-native";
import { safeAreaBottomHeight, SureGoods } from "../../util/AdapterUtil";
import { connect } from "react-redux";
import NavigationBar from "../../components/navigationBar";
import image from "../../assets/image";
import FlatListEmpty from "../../components/FlatListEmpty";
import NavigationService from "../../components/NavigationService";
import * as requestApi from "../../util/requestApi";

import _ from "lodash";
import FlatListFooter from "../../components/FlatListFooter";
import {ClassicsHeader, SmartRefreshControl} from "react-native-smartrefreshlayout";
class MOrderListScreen extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
        isRefreshing: false,
        searchText: "",
        data: [],
        loading: false,
        hasMore: true
    };
      this.debouncedGetData = _.debounce(this.getData.bind(this), 300);
  }

  componentDidMount() {
    this.getData();
  }

  componentWillUnmount() {

  }

  render() {
    const { data, hasMore } = this.state;
    return (
      <View style={{ flex: 1, backgroundColor: "#F9F9F9" }}>
        <NavigationBar
          navigation={this.props.navigation}
          isBack={true}
          title={"订单列表"}/>

          <ScrollView
              style={{marginTop:6, flex: 1 }}
              alwaysBounceVertical={true}
              refreshControl={
                  Platform.OS == "ios" ? (
                      <RefreshControl
                          refreshing={this.state.isRefreshing}
                          onRefresh={() => {
                              this._onRefresh();
                          }}
                          backgroundColor={"#F9F9F9"}
                      />
                  ) : (
                      <SmartRefreshControl
                          ref={ref => (this.rc = ref)}
                          renderHeader={<ClassicsHeader primaryColor="#F9F9F9" />}
                          onRefresh={() => {
                              this._onRefresh();
                          }}
                          enableLoadMore={false}
                          onLoadMore={() => {
                              this.getData();
                          }}
                      />
                  )
              }
          >
          <FlatList
            style={{ backgroundColor: "#fff" }}
            scrollEnabled={false}
            data={data}
            horizontal={false}
            keyExtractor={(item, index) => index.toString()}
            renderItem={this._renderItem}
            ListEmptyComponent={() => <FlatListEmpty />}
            // ListFooterComponent={() => (
            //     <FlatListFooter
            //         isShowBottom={false}
            //         show={data && data.length > 10 ? true : false}
            //         hasMore={hasMore}
            //     />
            // )}
            onEndReached={() => {
                if (data && data.length >= 10) {
                    //大于等于10 说明到了底部
                    //this.debouncedGetData();
                }
            }}
            onEndReachedThreshold={1}
          />
        </ScrollView>
        <View style={{ height: safeAreaBottomHeight }} />
      </View>
    );
  }

  //下拉刷新
  _onRefresh = () => {
    this.setState({ isRefreshing: true });
    this.getData();
  };

  _finishRefresh = () => {
    this.setState({
        loading: false
    });
    Platform.OS == "ios"
        ? this.setState({ isRefreshing: false })
        : this.rc && this.rc.finishRefresh();
  };

  getData = (isFirstPage = true) => {
    const { data, loading, hasMore } = this.state;
    if (isFirstPage || data == null || data.length === 0 || data.length < 10) {
        // 第一页
        requestApi
            .queryUsedMoney({page: 1 })
            .then(res => {
                this._finishRefresh();
                this.setState({
                    data: _.isArray(res)
                        ? res
                        : [],
                    hasMore: true
                });
            })
            .catch(() => {
                this._finishRefresh();
            });
    } else {
        if (
            data == null ||
            data.length === 0 ||
            data.length < 10 ||
            loading ||
            !hasMore
        ) {
            return;
        }
        this.setState({
            loading: true
        });
        let page = data.length / 10 + 1;
        requestApi
            .queryUsedMoney({page: page })
            .then(res => {
                this._finishRefresh();
                if (res != null || res.length == 0) {
                    Toast.show("没有更多数据了", 500);
                }
                let moreList = [];
                moreList   =_.isArray(res)
                    ? res
                    : [];
                let _data = [...data, ...moreList];
                let _hasMore = res.total === _data.length ? false : true;
                this.setState({
                    data: _data,
                    hasMore: _hasMore
                });
            })
            .catch(e => {
                this._finishRefresh();
            });
    }
  };

  _renderItem = ({ item }) => (
    <BillItem onPressItem={this._onPressItem.bind(this)} item={item} />
  );

  _onPressItem = id => {
    NavigationService.navigate("MBillDetailScreen", {
      orderId: id,
      reloadList: this.getData.bind(this, 1)
    });
  };
}

class BillItem extends PureComponent {
    _onPress = () => {
        this.props.onPressItem(this.props.item.orderId);
    };

    /*{
          companyName: "测试11111111111",
          payTime: "2019-05-24T02:25:52.000+0000",
          amount: 1,
          refundStatus: false,
          payMode: 1,
          receiveGoodsState:1
      }*/

    render() {
        return (
            <View style={{ height: 61 }}>
                <TouchableOpacity
                    style={{
                        flexDirection: "row",
                        height: 60,
                        marginLeft: 10,
                        marginTop: 2,
                        marginRight: 10,
                        marginBottom: 2,
                        alignItems: "center"
                    }}
                    onPress={this._onPress.bind(this)}
                >
                    <View
                        style={{
                            flex: 1,
                            marginLeft: 10,
                            paddingTop: 2,
                            marginRight: 10,
                            paddingBottom: 2,
                            justifyContent: "center",
                            alignItems: "flex-start"
                        }}
                    >
                        <Text style={{ color: "#606060", fontSize: 14 }} numberOfLines={1}>
                            {this.props.item.companyName}
                        </Text>
                        <View style={{ height: 12 }} />
                        <Text style={{ color: "#AAAAAA", fontSize: 12 }} numberOfLines={1}>
                            {this.props.item.payTime}
                        </Text>
                    </View>
                    <View
                        style={{
                            flex: 1,
                            marginLeft: 10,
                            paddingTop: 2,
                            marginRight: 10,
                            paddingBottom: 2,
                            justifyContent: "center",
                            alignItems: "flex-end"
                        }}
                    >
                        <Text style={{ color: "#606060", fontSize: 14 }} numberOfLines={1}>
                            ¥ {this.props.item.amount}
                        </Text>
                        <Text
                            numberOfLines={1}
                            style={[
                                this.props.item.refundAmount
                                    ? { color: "#F79646" }
                                    : { color: "#AAAAAA" },
                                { fontSize: 12 }
                            ]}
                        >
                            {this.props.item.refundAmount ? "有退款" : null}
                        </Text>
                        <View style={{ flexDirection: "row" }}>
                            <Text
                                numberOfLines={1}
                                style={[{ color: "#AAAAAA" }, { fontSize: 12 }]}
                            >
                                {this.props.item.payState === 1 ? "已支付" : "已关闭"}
                            </Text>

                            <Text
                                numberOfLines={1}
                                style={[{ color: "#AAAAAA" }, { fontSize: 12 }]}
                            >
                                {this.props.item.payMode === 2 ? "、货到付款" : null}
                            </Text>
                            <Text
                                numberOfLines={1}
                                style={[{ color: "#AAAAAA" }, { fontSize: 12 }]}
                            >
                                {this.props.item.receiveGoodsState === 0 ? "、待收货" : '、已收货'}
                            </Text>
                        </View>
                    </View>
                </TouchableOpacity>

                <View
                    style={{
                        marginLeft: 20,
                        height: 1,
                        backgroundColor: "#DDDDDD",
                        transform: [{ scaleY: 0.5 }]
                    }}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({});

export default connect(
  ({ userInfo }) => ({
    userInfo
  }),
  {}
)(MOrderListScreen);
